package mission_tour.solution;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import mission_tour.solution.tour_coupon.CouponAdapter;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class tour_main extends Activity implements ServerIp{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tour_main);

        items.event_list.removeAll(items.event_list);
        
        final Button hospitalinfo_btn = (Button) findViewById(R.id.hospitalinfo_btn);
        final Button productinfo_btn = (Button) findViewById(R.id.productinfo_btn);
        final Button oxquiz_btn = (Button) findViewById(R.id.oxquiz_btn);
        
        hospitalinfo_btn.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
					hospitalinfo_btn.setBackgroundResource(R.drawable.main_btn_l_down);
				}else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
					hospitalinfo_btn.setBackgroundResource(R.drawable.main_btn_l);
					Intent intent = new Intent(tour_main.this, tour_map.class);
					startActivityForResult(intent, 0);
					finish();
				}
					return false;
			}
		});
        
       

        productinfo_btn.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
					productinfo_btn.setBackgroundResource(R.drawable.main_btn_l_down);
				}else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
					productinfo_btn.setBackgroundResource(R.drawable.main_btn_l);
					Intent intent = new Intent(tour_main.this, tour_event_info.class);
					startActivityForResult(intent, 0);
					finish();
				}
					return false;
			}
		});
        
        
        
        
        oxquiz_btn.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
					oxquiz_btn.setBackgroundResource(R.drawable.main_btn_l_down);
				}else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
					oxquiz_btn.setBackgroundResource(R.drawable.main_btn_l);
					
					items.event_list.removeAll(items.event_list);
					
					AlertDialog.Builder q_level = new AlertDialog.Builder(tour_main.this)
	    			.setTitle(items.appname)
	    			.setMessage("퀴즈 난이도를 선택해 주세요")
	    			.setIcon(R.drawable.icon)
	    			.setPositiveButton("초급", new DialogInterface.OnClickListener(){
	    				@Override
	    				public void onClick(DialogInterface dialog, int which) {
	    					// TODO Auto-generated method stub
	    					final ProgressDialog nowloding = ProgressDialog.show(tour_main.this,"","OX 퀴즈를 불러오고 있습니다....",true);
	    			        
	    			        new Thread(new Runnable() {    
	    						@Override
	    						public void run() {				 
	    							try{
	    				    			
	    					    		URL url = null;
	    						        String resultString =null;
	    						  
	    					        	url = new URL(tour_oxquiz_call+"?app_type="+items.apptype+"&q_level="+items.q_level_easy);
	    							
	    					        	HttpURLConnection http = (HttpURLConnection)url.openConnection();  
	    					        	
	    					        	BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
	    					        	StringBuffer buffer = new StringBuffer();
	    								 
	    					        	int z;
	    					        	
	    								while((z=in.read()) != -1){
	    									buffer.append((char)z);
	    								}
	    								
	    								resultString= buffer.toString().trim();
	    								
	    					            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
	    					            factory.setNamespaceAware(true);
	    					            
	    					            boolean tagok = false;
	    					            
	    					            String[] quiz_call = null;
	    					            
	    					            XmlPullParser xpp = factory.newPullParser();
	    					            xpp.setInput(new StringReader(resultString));
	    					            
	    					            int eventType = xpp.getEventType();
	    					            
	    					            while (eventType != XmlPullParser.END_DOCUMENT) {
	    					                
	    					            	if(eventType == XmlPullParser.START_DOCUMENT) {
	    					                    System.out.println("Start document");
	    					                }
	    					            	
	    					            	if (eventType == XmlPullParser.END_DOCUMENT) {
	    					                    System.out.println("End document");
	    					                }
	    					            	
	    					            	if (eventType == XmlPullParser.START_TAG) {
	    					            		
	    					            		if(xpp.getName().equals("name")){
	    					            			tagok = true;
	    					            		}
	    					                }
	    					            	
	    					            	if (eventType == XmlPullParser.END_TAG) {
	    					                }
	    					            	
	    					            	if (eventType == XmlPullParser.TEXT) {
	    					            		if(tagok){
	    					            			quiz_call = xpp.getText().split(",");
	    					                	}
	    					            		quizs qs = new quizs("",quiz_call[0],"","","","","",Integer.parseInt(quiz_call[1]),0,quiz_call[2],Integer.parseInt(quiz_call[3]));
	    					            
	    					            		items.event_list.add(qs);
	    					                }
	    					                eventType = xpp.next();
	    					            }
	    					            
	    					            nowloding.cancel();
	    					            
	    					            Intent intent = new Intent(tour_main.this, tour_oxquiz.class);
	    								startActivityForResult(intent, 0);
	    								finish();
	    					    		
	    							} catch (MalformedURLException e) {
	    								// TODO Auto-generated catch block
	    								e.printStackTrace();
	    							} catch (IOException e) {
	    								// TODO Auto-generated catch block								
	    								runOnUiThread(new Runnable(){
	    						            @Override
	    						             public void run() {
	    						            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_main.this);
	    						    			nologin.setTitle(items.appname);
	    						    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
	    						    			nologin.setIcon(R.drawable.icon);
	    						    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
	    						    				@Override
	    						    				public void onClick(DialogInterface dialog, int which) {
	    						    					// TODO Auto-generated method stub
	    						    					moveTaskToBack(true);
	    						    					android.os.Process.killProcess(android.os.Process.myPid());
	    						    				}
	    						    			});
	    						    			nologin.show();
	    						             }
	    						        });
	    							}catch(Exception e){
	    								System.out.println(e.toString());
	    							}
	    						}
	    				    }).start();
	    				}
	    			})
	    			.setNeutralButton("고급", new DialogInterface.OnClickListener(){
	    				@Override
	    				public void onClick(DialogInterface dialog, int which) {
	    					// TODO Auto-generated method stub
	    					final ProgressDialog nowloding = ProgressDialog.show(tour_main.this,"","OX 퀴즈를 불러오고 있습니다....",true);
	    			        
	    			        new Thread(new Runnable() {    
	    						@Override
	    						public void run() {				 
	    							try{
	    				    			
	    					    		URL url = null;
	    						        String resultString =null;
	    						  
	    					        	url = new URL(tour_oxquiz_call+"?app_type="+items.apptype+"&q_level="+items.q_level_hard);
	    							
	    					        	HttpURLConnection http = (HttpURLConnection)url.openConnection();  
	    					        	
	    					        	BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
	    					        	StringBuffer buffer = new StringBuffer();
	    								 
	    					        	int z;
	    					        	
	    								while((z=in.read()) != -1){
	    									buffer.append((char)z);
	    								}
	    								
	    								resultString= buffer.toString().trim();
	    								
	    					            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
	    					            factory.setNamespaceAware(true);
	    					            
	    					            boolean tagok = false;
	    					            
	    					            String[] quiz_call = null;
	    					            
	    					            XmlPullParser xpp = factory.newPullParser();
	    					            xpp.setInput(new StringReader(resultString));
	    					            
	    					            int eventType = xpp.getEventType();
	    					            
	    					            while (eventType != XmlPullParser.END_DOCUMENT) {
	    					                
	    					            	if(eventType == XmlPullParser.START_DOCUMENT) {
	    					                    System.out.println("Start document");
	    					                }
	    					            	
	    					            	if (eventType == XmlPullParser.END_DOCUMENT) {
	    					                    System.out.println("End document");
	    					                }
	    					            	
	    					            	if (eventType == XmlPullParser.START_TAG) {
	    					            		
	    					            		if(xpp.getName().equals("name")){
	    					            			tagok = true;
	    					            		}
	    					                }
	    					            	
	    					            	if (eventType == XmlPullParser.END_TAG) {
	    					                }
	    					            	
	    					            	if (eventType == XmlPullParser.TEXT) {
	    					            		if(tagok){
	    					            			quiz_call = xpp.getText().split(",");
	    					                	}
	    					            		quizs qs = new quizs("",quiz_call[0],"","","","","",Integer.parseInt(quiz_call[1]),0,quiz_call[2],Integer.parseInt(quiz_call[3]));
	    					            
	    					            		items.event_list.add(qs);
	    					                }
	    					                eventType = xpp.next();
	    					            }
	    					            
	    					            nowloding.cancel();
	    					            
	    					            Intent intent = new Intent(tour_main.this, tour_oxquiz.class);
	    								startActivityForResult(intent, 0);
	    								finish();
	    					    		
	    							} catch (MalformedURLException e) {
	    								// TODO Auto-generated catch block
	    								e.printStackTrace();
	    							} catch (IOException e) {
	    								// TODO Auto-generated catch block								
	    								runOnUiThread(new Runnable(){
	    						            @Override
	    						             public void run() {
	    						            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_main.this);
	    						    			nologin.setTitle(items.appname);
	    						    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
	    						    			nologin.setIcon(R.drawable.icon);
	    						    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
	    						    				@Override
	    						    				public void onClick(DialogInterface dialog, int which) {
	    						    					// TODO Auto-generated method stub
	    						    					moveTaskToBack(true);
	    						    					android.os.Process.killProcess(android.os.Process.myPid());
	    						    				}
	    						    			});
	    						    			nologin.show();
	    						             }
	    						        });
	    							}catch(Exception e){
	    								System.out.println(e.toString());
	    							}
	    						}
	    				    }).start();
	    				}
	    			});
					q_level.show();
				}
					return false;
			}
		});
    }
    
    public boolean onKeyDown( int KeyCode, KeyEvent event ){
		if( event.getAction() == KeyEvent.ACTION_DOWN ){
			// 이 부분은 특정 키를 눌렀을때 실행 된다.
			// 만약 뒤로 버튼을 눌럿을때 할 행동을 지정하고 싶다면
			
			if( KeyCode == KeyEvent.KEYCODE_BACK ){
			items.back_push++;
			 //여기에 뒤로 버튼을 눌렀을때 해야할 행동을 지정한다
				long currentTime = System.currentTimeMillis();
				if(items.back_push == 1){
					items.touchTime = System.currentTimeMillis();
					Toast t =  Toast.makeText(tour_main.this,"종료 하시려면\n한번 더 뒤로가기 버튼을 눌러주세요",Toast.LENGTH_SHORT);
				    t.setDuration(2000);
				    t.show();
				          
				    new Thread(new Runnable() {    
						@Override
						public void run() {
							try {
								Thread.sleep(2000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
								items.back_push=0;
							}
				    	}).start();
				}else if(items.back_push == 2){
					if(currentTime - items.touchTime <= 2000 ){
						finish();
						return super.onKeyDown(KeyCode, event);
					}					
				}
				return true;
			}
		}
		return super.onKeyDown(KeyCode, event);
	}
    public boolean onCreateOptionsMenu(Menu menu){
    	getMenuInflater().inflate(R.menu.quick, menu);
		return true;   	
    }

    public boolean onOptionsItemSelected(MenuItem item){
    	if(item.getItemId() == R.id.map_go){
    		startActivity(new Intent(this,tour_map.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.event_go){
    		startActivity(new Intent(this,tour_event_info.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.myinfo_go){
    		startActivity(new Intent(this,tour_myinfo.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.coupon_go){
    		startActivity(new Intent(this,tour_coupon.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.help_go){
    		startActivity(new Intent(this,tour_help.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.oxquiz_go){
    		items.event_list.removeAll(items.event_list);

    		new Thread(new Runnable() {    
				@Override
				public void run() {
					runOnUiThread(new Runnable(){
						 @Override
						 public void run() {
							 AlertDialog.Builder q_level = new AlertDialog.Builder(tour_main.this)
				    			.setTitle(items.appname)
				    			.setMessage("퀴즈 난이도를 선택해 주세요")
				    			.setIcon(R.drawable.icon)
				    			.setPositiveButton("초급", new DialogInterface.OnClickListener(){
				    				@Override
				    				public void onClick(DialogInterface dialog, int which) {
				    					// TODO Auto-generated method stub
				    					final ProgressDialog nowloding = ProgressDialog.show(tour_main.this,"","OX 퀴즈를 불러오고 있습니다....",true);
				    			        
				    			        new Thread(new Runnable() {    
				    						@Override
				    						public void run() {				 
				    							try{
				    				    			
				    					    		URL url = null;
				    						        String resultString =null;
				    						  
				    					        	url = new URL(tour_oxquiz_call+"?app_type="+items.apptype+"&q_level="+items.q_level_easy);
				    							
				    					        	HttpURLConnection http = (HttpURLConnection)url.openConnection();  
				    					        	
				    					        	BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
				    					        	StringBuffer buffer = new StringBuffer();
				    								 
				    					        	int z;
				    					        	
				    								while((z=in.read()) != -1){
				    									buffer.append((char)z);
				    								}
				    								
				    								resultString= buffer.toString().trim();
				    								
				    					            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				    					            factory.setNamespaceAware(true);
				    					            
				    					            boolean tagok = false;
				    					            
				    					            String[] quiz_call = null;
				    					            
				    					            XmlPullParser xpp = factory.newPullParser();
				    					            xpp.setInput(new StringReader(resultString));
				    					            
				    					            int eventType = xpp.getEventType();
				    					            
				    					            while (eventType != XmlPullParser.END_DOCUMENT) {
				    					                
				    					            	if(eventType == XmlPullParser.START_DOCUMENT) {
				    					                    System.out.println("Start document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_DOCUMENT) {
				    					                    System.out.println("End document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.START_TAG) {
				    					            		
				    					            		if(xpp.getName().equals("name")){
				    					            			tagok = true;
				    					            		}
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_TAG) {
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.TEXT) {
				    					            		if(tagok){
				    					            			quiz_call = xpp.getText().split(",");
				    					                	}
				    					            		quizs qs = new quizs("",quiz_call[0],"","","","","",Integer.parseInt(quiz_call[1]),0,quiz_call[2],Integer.parseInt(quiz_call[3]));
				    					            
				    					            		items.event_list.add(qs);
				    					                }
				    					                eventType = xpp.next();
				    					            }
				    					            
				    					            nowloding.cancel();
				    					            
				    					            Intent intent = new Intent(tour_main.this, tour_oxquiz.class);
				    								startActivityForResult(intent, 0);
				    								finish();
				    					    		
				    							} catch (MalformedURLException e) {
				    								// TODO Auto-generated catch block
				    								e.printStackTrace();
				    							} catch (IOException e) {
				    								// TODO Auto-generated catch block								
				    								runOnUiThread(new Runnable(){
				    						            @Override
				    						             public void run() {
				    						            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_main.this);
				    						    			nologin.setTitle(items.appname);
				    						    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
				    						    			nologin.setIcon(R.drawable.icon);
				    						    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
				    						    				@Override
				    						    				public void onClick(DialogInterface dialog, int which) {
				    						    					// TODO Auto-generated method stub
				    						    					moveTaskToBack(true);
				    						    					android.os.Process.killProcess(android.os.Process.myPid());
				    						    				}
				    						    			});
				    						    			nologin.show();
				    						             }
				    						        });
				    							}catch(Exception e){
				    								System.out.println(e.toString());
				    							}
				    						}
				    				    }).start();
				    				}
				    			})
				    			.setNeutralButton("고급", new DialogInterface.OnClickListener(){
				    				@Override
				    				public void onClick(DialogInterface dialog, int which) {
				    					// TODO Auto-generated method stub
				    					final ProgressDialog nowloding = ProgressDialog.show(tour_main.this,"","OX 퀴즈를 불러오고 있습니다....",true);
				    			        
				    			        new Thread(new Runnable() {    
				    						@Override
				    						public void run() {				 
				    							try{
				    				    			
				    					    		URL url = null;
				    						        String resultString =null;
				    						  
				    					        	url = new URL(tour_oxquiz_call+"?app_type="+items.apptype+"&q_level="+items.q_level_hard);
				    							
				    					        	HttpURLConnection http = (HttpURLConnection)url.openConnection();  
				    					        	
				    					        	BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
				    					        	StringBuffer buffer = new StringBuffer();
				    								 
				    					        	int z;
				    					        	
				    								while((z=in.read()) != -1){
				    									buffer.append((char)z);
				    								}
				    								
				    								resultString= buffer.toString().trim();
				    								
				    					            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				    					            factory.setNamespaceAware(true);
				    					            
				    					            boolean tagok = false;
				    					            
				    					            String[] quiz_call = null;
				    					            
				    					            XmlPullParser xpp = factory.newPullParser();
				    					            xpp.setInput(new StringReader(resultString));
				    					            
				    					            int eventType = xpp.getEventType();
				    					            
				    					            while (eventType != XmlPullParser.END_DOCUMENT) {
				    					                
				    					            	if(eventType == XmlPullParser.START_DOCUMENT) {
				    					                    System.out.println("Start document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_DOCUMENT) {
				    					                    System.out.println("End document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.START_TAG) {
				    					            		
				    					            		if(xpp.getName().equals("name")){
				    					            			tagok = true;
				    					            		}
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_TAG) {
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.TEXT) {
				    					            		if(tagok){
				    					            			quiz_call = xpp.getText().split(",");
				    					                	}
				    					            		quizs qs = new quizs("",quiz_call[0],"","","","","",Integer.parseInt(quiz_call[1]),0,quiz_call[2],Integer.parseInt(quiz_call[3]));
				    					            
				    					            		items.event_list.add(qs);
				    					                }
				    					                eventType = xpp.next();
				    					            }
				    					            
				    					            nowloding.cancel();
				    					            
				    					            Intent intent = new Intent(tour_main.this, tour_oxquiz.class);
				    								startActivityForResult(intent, 0);
				    								finish();
				    					    		
				    							} catch (MalformedURLException e) {
				    								// TODO Auto-generated catch block
				    								e.printStackTrace();
				    							} catch (IOException e) {
				    								// TODO Auto-generated catch block								
				    								runOnUiThread(new Runnable(){
				    						            @Override
				    						             public void run() {
				    						            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_main.this);
				    						    			nologin.setTitle(items.appname);
				    						    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
				    						    			nologin.setIcon(R.drawable.icon);
				    						    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
				    						    				@Override
				    						    				public void onClick(DialogInterface dialog, int which) {
				    						    					// TODO Auto-generated method stub
				    						    					moveTaskToBack(true);
				    						    					android.os.Process.killProcess(android.os.Process.myPid());
				    						    				}
				    						    			});
				    						    			nologin.show();
				    						             }
				    						        });
				    							}catch(Exception e){
				    								System.out.println(e.toString());
				    							}
				    						}
				    				    }).start();
				    				}
				    			});
								q_level.show();
						 }
					 });
				}
		    }).start();
    	}
		return false;
    }
}